package com.dotflat.training.controller;

import com.dotflat.rest.controller.RestfulBaseController;
import com.dotflat.training.domain.OTCourse;
import com.dotflat.training.domain.OTCourseBookRecord;
import com.dotflat.training.po.OTCourseBookRecordPO;
import com.dotflat.training.repository.OTCourseBookRecordRepository;
import com.dotflat.training.service.OTCourseBookRecordService;
import com.dotflat.training.service.OTCourseService;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.model.StatusResponse;
import com.matt.foundation.model.ErrorCode;
import com.matt.service.remoteCall.SsoCallService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.matt.foundation.constant.RequestConstant.TICKET;

@RestController
@RequestMapping("/api/otcourse/booking_record")
@Slf4j
@Api(tags = "线下培训课 - 签到预约记录")
public class OTCourseBookRecordController extends RestfulBaseController<OTCourseBookRecord, OTCourseBookRecordService, OTCourseBookRecordPO> {

    @Autowired
    private OTCourseService otCourseService;

    @Autowired
    private OTCourseBookRecordRepository bookRecordRepository;

    @Autowired
    public void setBaseService(OTCourseBookRecordService service){
        super.setBaseService(service);
    }

    @Autowired
    private SsoCallService ssoCallService;

    @ApiOperation(value = "增加一条记录")
    @PostMapping()
    @Override
    public StatusResponse add(@RequestHeader(TICKET) String ticket, OTCourseBookRecordPO param){
        StaffDTO staff = cache.getStaff(ticket);

        String courseId = param.getOfflineCourseId();
        OTCourse course = otCourseService.get(staff.getAreaId(), staff.getId(), courseId);

        if (course == null){
            throw new BusinessException(ErrorCode.COURSE_NOT_EXISTD, "培训课不存在");
        }

        if (param.getBooked() != null){
            param.setBookedAt(new Date());
            param.setChecked(null);
            param.setStaffId(null);

            param.setTargetStaff(staff);
        }else
        if (param.getChecked() != null){
            param.setCheckedAt(new Date());

            if (StringUtils.isEmpty(param.getStaffId())){
                throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "需要指定签到对象");
            }

            StaffDTO targetStaff = ssoCallService.getStaffDTO(ticket, param.getStaffId());
            if (targetStaff == null){
                throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "错误的签到对象");
            }

            param.setTargetStaff(targetStaff);

        }else{
            throw new BusinessException(ErrorCode.PARAM_CAN_NOT_BLANK, "参数错误");
        }

        if (param.getId() == null){
            //是否需要复用对象
            OTCourseBookRecord exist = bookRecordRepository.findFirstByAreaIdAndStaffIdAndOfflineCourseIdAndDeletedIsFalse(staff.getAreaId(), param.getTargetStaff().getId(), param.getOfflineCourseId());
            if (exist != null){
                param.setId(exist.getId());
            }
        }

        OTCourseBookRecord ret = baseService.add(staff.getAreaId(), staff.getId(), param, o->{
            //补充字段，仅在预约的时候需要补充数据
            if (StringUtils.isNotEmpty(o.getStaffId()) && !o.getStaffId().equals(param.getTargetStaff().getId())){
                throw new BusinessException(ErrorCode.STAFF_HAS_NO_ROLE, "意料之外的错误");
            }
            o.setStaffId(param.getTargetStaff().getId());
            o.setStaffHeadImg(param.getTargetStaff().getHeadImgUrl());
            o.setStaffName(param.getTargetStaff().getRealName());

            if (param.getChecked() != null){
                o.setCheckedBy(staff.getId());
            }
        });

        if (course.getVisitorCount() == null){
            course.setVisitorCount(1);
        }else {
            course.setVisitorCount(course.getVisitorCount() + 1);
        }
        otCourseService.update(course);

        List<OTCourseBookRecord> tmp = new ArrayList<>();
        tmp.add(ret);

        return StatusResponse.success(tmp);
    }

}
